<?php

namespace app\api\controller\Account;

//use addons\txim\TLSSigAPI;
//use app\admin\controller\userkanban\Customer;
//use app\admin\controller\KeywordsCompany;
use app\admin\model\Admin;
use app\admin\model\AdminBasicZoom;
use app\admin\model\AdminLog;
use app\admin\model\AuthGroupAccessZoom;
use app\common\controller\Api;
//use app\common\controller\Callfunc;
use app\common\controller\Callfunc;
use app\common\library\Ems;
use app\common\library\Iden;
use app\common\library\Sms;
use app\admin\model\Account;
use app\common\library\Token;
use fast\Random;
use think\Config;
use think\Cookie;
use think\Db;
use think\Hook;
use think\Session;
use think\Validate;

/**
 * 用户接口
 */
class  Index extends Api
{
    protected $noNeedLogin = ['index','testtoken','login', 'loginNew', 'mobilelogin', 'register','logout', 'resetpwd', 'changeemail', 'changemobile', 'third','getUerInfo','register_two'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
       // $uInfo = $this->auth->getUserInfo();
      //  print_r ($uInfo);
       // echo '~~~~';die;
//        $u = Api::getinfo();
//        print_r($u);
//        echo '+++++=';
//
//        echo $this->auth->getToken();
//        echo '====';die;
        $userid =1;
        $token = Api::getRefreshtoken($userid);//通过用户uid获取token
       // $token = '';
        echo $token;
        echo '=====';
        //$token ='8d1f3cb7665a261d68529bacf34c5fb4b54d65d8';
        $uid =  \app\common\library\Token::get($token);//通过token获取用户信息
        print_R($uid);
        echo 'ddd';die;
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    public function testtoken(){
        $userid =1;
        $token = Api::getRefreshtoken($userid);
        $this->success('', ['welcome' => $this->auth->nickname,'token'=>$token]);
    }
    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function loginold()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = Account::getByMobile($mobile);

        if ($user) {
            $user_basic= AdminBasicZoom::get(['account_id'=>$user->id]);//查找用户基本信息表中有无此用户，无则插入
            if(empty($user_basic)){
                $admin = Admin::get(['account_id'=>$user->id]);
                if(empty($admin)){
                    $this->error(__('数据异常'));
                }
                $admin_id = $admin->id;
                //4 创建Zoom用户基本信息表
                $basic_admin['account_id'] = $user->id;
                $basic_admin['admin_id'] = $admin_id;
                $basic_admin['serial'] = $user->serial;
                $basic_admin['avatar'] = $user->avatar;;
                $basic_admin['ctime'] = time();
                $basic_admin['source'] = Account::USER_SOURCE_99;
                $basic_admin['joinip'] = real_ip();;
                $basic_admin['loginip'] = real_ip();;

                $admin_basic =  new AdminBasicZoom();//注册用户基本信息表
                $admin_basic_r = $admin_basic->save($basic_admin);
                if (!$admin_basic_r){
                    $this->error('用户基本信息注册失败，请重试', null, ['token' => $this->request->token()]);
                }

            }

            if ($user_basic->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->mobile_direct($user->id);
        } else {
            $ret = $this->auth->mobile_register($mobile);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            // $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $this->auth->getUserinfo(),200);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 用户登录
     */
   /* public function login888()
    {
        $url = $this->request->get('url', 'index/index');
        // $url = substr($url,0,strpos($url, '?')).'?ref=addtabs';
        if ($this->auth->isLogin()) {
            //$this->success(__("You've logged in, do not login again"), $url, ['url'=>$url]);
            $this->success(__('You have logged in, do not login again'),  $this->auth->getUserInfo(),200);
        }

        if ($this->request->isPost()) {
            $username = $this->request->request('username');
            $password = $this->request->request('password');
            $keeplogin = $this->request->request('keeplogin');
            //$token = $this->request->post('__token__');
            //$go_type = $this->request->post('go_type');

            $rule = [
                'username'  => 'require|length:3,20',
                'password'  => 'require|length:3,30',
                '__token__' => 'token',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
              //  '__token__' => $token,
            ];

            $msg = [
                'username.require'   => __('Account cannot be empty'),
                'username.length'    => __('Account must be 3-20 characters'),
            ];


            //  登录是否开启图片验证码
            if (Config::get('fastadmin.login_captcha')) {
                $rule['captcha'] = 'require|captcha';
                $data['captcha'] = $this->request->request('captcha');
                $validate = new Validate($rule, $msg, ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
            }else{
                $validate = new Validate($rule, $msg, ['username' => __('Username'), 'password' => __('Password')]);
            }

            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), $url, ['token' => $this->request->token()]);
            }
            $account_result = $this->auth->accountLogin($username, $password, $keeplogin ? 0 : (86400 * 15));

            // 账号登录出错
            if (!$account_result){
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error(__($msg), $url, ['token' => $this->request->token()]);
            }
            $account = Session::get('account');

            //直接登录admin，清除account的session
             $admin_id = Db::name('admin')->where('account_id', '=', $account['id'])->where('status', '=', 'normal')->field('id')->find()['id'];

            AdminLog::setTitle(__('Login'));
            $result = $this->auth->admin_login($username, $password, $admin_id, $keeplogin ? (86400 * 15) : 0,$this->request->header("host"));
            if ($result === true) {
                Hook::listen("admin_login_after", $this->request);
               $this->success(__('Sign up successful'),  $this->auth->getUserinfo(),200);
                //$this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'avatar' => $this->auth->avatar, 'token'=>$this->auth->token]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error(__($msg), $url, ['token' => $this->request->token()]);
            }
        }
        if ($this->auth->autologin()) {
           // $this->redirect($url);
            $this->success(__('Sign up successful'),  $this->auth->getUserinfo(),200);
        }
        Hook::listen("admin_login_init", $this->request);
        $this->success(__('登录初始化,没接收到登录参数'), 'index/login');
       // $this->success(__('Sign up successful'),  $this->auth->getUserInfo(),200);
       // return $this->view->fetch(Config::get('tplset.login'));
    }*/

    /**
     * 登录
     * @param string $login_type     登录形式，验证码登录公用此方法
     * @param string $username
     * @param string $loginEquipment  设备类型
     * @param string $retype 返回类型  （默认为空即可，返回json类型， 如果返回数组，请随便给个值）
     */
    public function login($login_type = 'login', $username = '', $loginEquipment = '', $retype = '')
    {
        if ($login_type == 'login') {
            $username = str_replace(' ', '', $this->request->request('username'));
            $password = $this->request->request('password');
            $loginEquipment = strtolower($this->request->request('loginEquipment', 'win'));
            if (!$username) {
                $this->error('请输入账号');
            }
            if (empty($password)) {
                $this->error('请输入密码');
            }
            /*if (!$loginEquipment) {
                $this->error(__('请输入设备类型'));
            }*/
        }else{
            $password = '';
        }

        // 登录第一步 (更新account的同时， 更新本地token相关值，（注意不是account表里的token。）)
        $accountlogin = $this->auth->loginAccountNew($username, $password, $login_type);
        if (!$accountlogin) {
            $this->error($this->auth->getError());
        }
        // 模拟登录相应admin账号 (此方法最后调用的directNew()方法完成了 user_token表 的数据更新)
        $adminlogin = $this->auth->loginNew($username, $password, $accountlogin['account_id'], $accountlogin['token']);

        $userInfo = [];
        if ($adminlogin) {
            $userInfo = $this->auth->getUserinfo();
        }else{
            $this->error($this->auth->getError());
        }

        if ($retype != '') {
            return $userInfo;
        }else{
            $this->success(__('登陆成功'), $userInfo, 200);
        }
    }

    /**
     * 注册
     */
    public function register()
    {
        $url = $this->request->request('url', 'index/index');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not register again'), $url);
        }
        if ($this->request->isPost()) {
           //$username = $this->request->request('username');//手机号
            $nickname = $this->request->request('nickname');//姓名
            $password = $this->request->request('password');
            $mobile = $this->request->request('mobile', '');
            $captcha = $this->request->request('captcha', '');
            //$token = $this->request->request('__token__');
            $rule = self::chkrule();
            $msg = self::chkmsg();

            $data = [
//                'username'  => $username,
                'nickname'  => $nickname,
                'password'  => $password,
                'mobile'    => $mobile,
                'captcha'   => $captcha,
               // '__token__' => $token,
            ];

            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), ['token' => $this->request->token()]);
            }
            if (strlen(str_replace(' ', '', $password)) != strlen($password)) {
                $this->error(__('抱歉，不建议使用包含空格的密码'));
            }
            // 校验验证码
            $captcha_result = Sms::check($mobile, $captcha, 'register');
            if(!$captcha_result){
                $this->error(__('Captcha is incorrect'));
            }
            // 处理数据
            $params = $this->request->param();
            $params['salt'] = pwdSalt();
            $params['password'] = md5(md5($params['password']) . $params['salt']);
            $params['createtime'] = time(); //创建时间为当前时间
            $params['updatetime'] = time(); //更新时间为当前时间
            $params['serial'] = Callfunc::makeUuid();     //---  生成唯一识别码
            $params['avatar'] = config('default_avatar');
            $params['joinip'] = request()->ip(0,false);
           // $params['loginip'] = $this->request->header("host");
            $params['loginip'] = request()->ip(0,false);

            $userToken = zoom_token();
            $params['token'] = $userToken;
            $params['token_zoom'] = $userToken;//来自zoom表中的token
            $params['username'] = $params['mobile'];
            $params['source'] = Account::USER_SOURCE_99;//用户来源 99 代表onzoom用户
            //print_r($params);die;
            // 1、判断账号表是否存在数据
            $account = Db::name('account')->where('mobile', '=', $mobile)->find();

            if ($account){
//                if (Config::get('apiSwitches.im')){
//                    if ($account['TLS']!=1 | $account['TLS'] === NULL){
//                        // 将新注册的账号添加到云通信TLS系统中
//                        $TLSapi = new TLSSigAPI();
//                        $tls_result = $TLSapi->accountImport($params['username']);
//                        if ($tls_result){
//                            $TLS = 1;
//                        }else{
//                            $TLS = 0;
//                        }
//                        Db::name('account')->where('username', '=', $mobile)->update(['TLS'=>$TLS]);
//                    }
//                }

                    // 2、判断admin用户是否有举办人角色
                    $admin_count = Db::name('auth_group_access_zoom')->alias('aga')
                        ->join('admin a', 'aga.uid=a.id', 'LEFT')
                        ->where('a.account_id', '=', $account['id'])
                        //->where('aga.group_id', '=', 2)//2为举办人
                        ->count();

                    if ($admin_count){
                        $this->error(__('手机号已存在'), 'admin/index/login', ['token' => $this->request->token()]);
                    }
                    // 已最新的密码为准
                    Db::name('account')->where('id', '=', $account['id'])->update(['password'=>$params['password'], 'salt'=>$params['salt']]);

                $account_id = $account['id'];
            }else{
                //2、创建账号
                $account_field = Db::name('account')->getTableFields();
                $account_params = array_filter(array_intersect_key($params, array_flip($account_field)));
//                if (Config::get('apiSwitches.im')){
//                    // 将新注册的账号添加到云通信TLS系统中
//                    $TLSapi = new TLSSigAPI();
//                    $tls_result = $TLSapi->accountImport($params['username']);
//                    if ($tls_result){
//                        $account_params['TLS'] = 1;
//                    }else{
//                        $account_params['TLS'] = 0;
//                    }
//                }
             //   var_dump($account_params);
               // echo 'dd';die;
                $account_id = Db::name('account')->insertGetId($account_params);
                if (!$account_id){
                    $this->error(__('注册失败，请重试'), null, ['token' => $this->request->token()]);
                }
            }

            // 开启事务
            Db::startTrans();
            try{

                //3、创建admin用户
                // 获取admin表的字段名称
                //$params['serial'] = selfserial();
                $admin_field = Db::name('admin')->getTableFields();
                $admin_params = array_filter(array_intersect_key($params, array_flip($admin_field)));
                $admin_params['account_id'] = $account_id;

                $admin = new Admin();
                $result_admin = $admin->save($admin_params);
                if (!$result_admin){
                    $this->error('注册失败，请重试', null, ['token' => $this->request->token()]);
                }

                //4 创建Zoom用户基本信息表
                $basic_admin['account_id'] = $account_id;
                $basic_admin['admin_id'] = $admin['id'];
                $basic_admin['serial'] = $params['serial'];
                $basic_admin['avatar'] = config('default_avatar');
                $basic_admin['ctime'] = time();
                $basic_admin['source'] = $params['source'];
                $basic_admin['joinip'] = $params['joinip'];
                $basic_admin['loginip'] = $params['loginip'];

                $admin_basic =  new AdminBasicZoom();//注册用户基本信息表
                $admin_basic_r = $admin_basic->save($basic_admin);
                if (!$admin_basic_r){
                    $this->error('用户基本信息注册失败，请重试', null, ['token' => $this->request->token()]);
                }
                $map['uid'] = $admin['id'];
              //  $map['group_id'] = AuthGroupAccessZoom::SPONSOR;
                $admin_count = Db::name('auth_group_access_zoom')
                    ->where($map)
                    ->count();

                if (!$admin_count){//当没有举办人的权限时加入举办的角色
                    $aga_result = AuthGroupAccessZoom::create(['uid'=>$admin['id'], 'group_id'=>AuthGroupAccessZoom::SPONSOR]);
                    if ($aga_result === false) {
                        $this->error(model('AuthGroupAccessZoom')->getError());
                    }
                }
                unset($map);
                unset($basic_admin);
               // unset($params);
                Db::commit();
            }catch (\Exception $e){
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }

            // 7、注册成功进行登录
            AdminLog::setTitle(__('Login'));
            //$result = $this->auth->admin_login($mobile, $password, $admin['id'], (86400 * 15),$params['joinip']);
            //-- 注册成功后处理登陆 ，要和前端登陆保持一致
            $accountlogin = $this->auth->loginAccountNew($mobile, $password, 'login');
            if (!$accountlogin) {
                $this->error($this->auth->getError());
            }
            // 模拟登录相应admin账号 (此方法最后调用的directNew()方法完成了 user_token表 的数据更新)
            $adminlogin = $this->auth->loginNew($mobile, $password, $accountlogin['account_id'], $accountlogin['token']);

            $userInfo = [];
            if ($adminlogin) {
                $userInfo = $this->auth->getUserinfo();
            }else{
                $this->error($this->auth->getError());
            }
            $this->success(__('注册成功'), $userInfo, 200);
            /*if ($result === true) {
                unset($params);
                Hook::listen("admin_login_after", $this->request);
                //$this->success(__('Sign up successful'),  ['id' => $this->auth->id, 'mobile' => $mobile, 'avatar' => $this->auth->avatar, 'token'=>$this->auth->token]);
                $this->success('注册成功',  $this->auth->getUserinfo(),200);
            }else{
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }*/
        }

        Hook::listen("admin_register_init", $this->request);
        $this->error(__('Invalid parameters'));
    }

    /**
     * 注册完善第二步信息
     * 注册完完善个人信息
     */
    public function register_two()
    {
        if ($this->request->isPost()) {
            $company = $this->request->request('company');//公司名称
            $position = $this->request->request('position');//职位
            $email = $this->request->request('email');
            $company_name = str_replace(' ', '', $company);
            $position = str_replace(' ', '', $position);
//            $id = $this->request->request('uid');
//            if (!$id) {
//                $this->error(__('获取用户id失败'));
//            }
            $r = $this->auth->getUserinfo();
            if(empty($r)){
                $this->error('注册失败，请重试', null, 401);
            }
            $id = $r['id'];
            $id = Iden::decrypt($id);
            // 验证
            if (!$company_name) {
                $this->error(__('Please enter your company name'));
            }
//            if (!$position) {
//                $this->error(__('Please enter your position'));
//            }

//            $company = \app\admin\model\Company::get($this->auth->company_id);
//            if (!$company){
//                $this->error(__('Company information does not exist'));
//            }
            $admin_basic = AdminBasicZoom::get(['admin_id' => $id]);
            if (!$admin_basic) {
                $this->setError('Username is incorrect');
                return false;
            }
            $admin_basic->email = $email;
            $admin_basic->position = $position;
            $admin_basic->company = $company_name;
            $admin_basic->save();
            if (!$admin_basic) {
                $this->error(__('完善个人信息失败'), null, ['token' => $this->request->token()]);
            } else {
                $this->success('信息完善成功', $this->auth->getUserinfo(), 200);
            }

        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        //$uInfo = $this->auth->getUserinfo();
        $this->auth->logout();
        $this->success(__('Logout successful'),  [],200);
    }
    /*public function logout()
    {
        $uInfo = $this->auth->getUserinfo();
        //print_R($uInfo);die;
        if(empty($uInfo)){
            $this->error(__('用户已退出'), null, 0);
        }
        $admin_id = Iden::decrypt($uInfo['id']);
        if(empty($admin_id)){
            $this->error(__('获取用户信息失败'), null, 0);
        }
        //$admin = AdminBasicZoom::get(['admin_id'=>$admin_id]);
        $admin = Admin::get($admin_id);
        $admin->prevtime = $admin->logintime;
        $admin->save();
        $this->auth->logout();
        Hook::listen("admin_logout_after", $this->request);
        $this->success(__('Logout successful'), ['token' => $uInfo['token']],200);
    }*/



    /**
     * 修改会员个人信息
     *
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwdold()
    {
        $type = $this->request->request("type");
        $mobile = $this->request->request("mobile");
        $email = $this->request->request("email");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /***
     * 找回密码
     */
    public function resetpwd(){

        $params = $this->request->param();
        $captcha = $params("captcha");
        $new_password = $params['password'];
        $confirm_password = $params['confirm_password'];
        if (!$captcha) {
            $this->error(__('Invalid parameters'));
        }
        // 校验
        if (!$params['mobile']) {
            $this->error(__('Please enter your mobile'));
        }
        if (!Validate::regex($params['mobile'], "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $account_info = Db::name('account')->where(['username'=>$params['mobile']])->field('id')->find();
        if (!$account_info) {
            $this->error(__('This number is not registered'));
        }
        if (!$new_password) {
            $this->error(__('Please enter a new password'));
        }
        if (!$confirm_password) {
            $this->error(__('Please enter the confirmation password'));
        }
        if (strlen(str_replace(' ', '', $new_password)) != strlen($new_password)) {
            $this->error(__('Sorry, the password cannot contain Spaces'));
        }
        if ((strlen($new_password) < 6) || strlen($new_password) > 17) {
            $this->error(__('Sorry, password length must be 6 or more bits and less than 18 bits'));
        }
        if ($new_password != $confirm_password) {
            $this->error(__('The passwords are different'));
        }

        // 校验验证码
        $captcha_result = Sms::check($params['mobile'], $params['captcha'], 'resetpwd');
        if(!$captcha_result){
            $this->error(__('Captcha is incorrect'));
        }
        $params['salt'] = Random::alnum();
        $params['password'] = md5(md5($params['password']) . $params['salt']);
        $account_field = Db::name('admin')->getTableFields();
        $account_params = array_filter(array_intersect_key($params, array_flip($account_field)));
        $account_result = Db::name('account')->where('mobile', '=', $params['mobile'])->update($account_params);
        if (!$account_result){
            $this->error(__('重置密码失败，请重试'));
        }
        $admin_field = Db::name('admin')->getTableFields();
        $admin_params = array_filter(array_intersect_key($params, array_flip($admin_field)));
        $admin_result = Db::name('admin')->where('mobile', '=', $params['mobile'])->update($admin_params);
        $this->success(__('重置密码成功，即将跳转...'), 'index/login',200);
    }
    /*
     * 验证规则
     */
    static public function chkrule(){
        $rule = [
//                'username'  => 'require|length:3,30|unique:admin',
            'nickname'  => 'require|length:0,20',
            'password'  => 'require|length:6,18',
            'mobile'    => 'require|regex:/^1\d{10}$/',
            'captcha'   => 'require|regex:/^\d{4}$/',
            '__token__' => 'token',
        ];

        return $rule;
    }

    /*
     * 验证规则提示
     */
    static public function chkmsg(){
        $msg = [
//                'username.require' => 'Username can not be empty',
//                'username.length'  => 'Username must be 3 to 30 characters',
//                'user.unique'      => 'Username already exist',
            'nickname.require' => 'nickname can not be empty',
            'nickname.length'  => 'nickname must be 3 to 20 characters',
            'password.require' => 'Password can not be empty',
            'password.length'  => 'Sorry, password length must be 6 or more bits and less than 18 bits',
            'captcha.require'  => 'Captcha can not be empty',
            'captcha.regex'    => 'Captcha must be 4 numbers',
            'mobile.regex'     => 'Mobile is incorrect',
            'mobile.require'   => 'Mobile can not be empty',
        ];

        return $msg;
    }

    public function getUerInfo()
    {
        $uInfo = $this->auth->getUserinfo();

        $this->success(__('Logout successful'), ['data' => !empty($uInfo) ? $uInfo:''],200);
    }


}
